package com.shengqiang.cloud.ups.dao.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.MybatisConfiguration;
import com.baomidou.mybatisplus.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.enums.DBType;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.util.ObjectUtils;

import javax.sql.DataSource;

/**
 * Druid的DataResource配置类  主库
 *
 * @author shengqiang.wu
 *
 *         凡是被Spring管理的类，实现接口 EnvironmentAware 重写方法 setEnvironment 可以在工程启动时，
 *         获取到系统环境变量和application配置文件中的变量。 还有一种方式是采用注解的方式获取 @value("${变量的key值}")
 *         ：获取application配置文件中的变量。 这里采用第一种要方便些
 *
 */
@Configuration
@MapperScan(basePackages = MasterDruidDataSourceConfig.PACKAGE,sqlSessionFactoryRef = "masterSqlSessionFactory")
public class MasterDruidDataSourceConfig implements EnvironmentAware {

    static final String PACKAGE="com.shengqiang.cloud.ups.dao.repository.master";
    static final String MAPPERLOCATIONS="classpath:/mapper/*Mapper.xml";

    @Autowired
    private ResourceLoader resourceLoader = new DefaultResourceLoader();

    @Autowired(required = false)
    private Interceptor[] interceptors;

    private RelaxedPropertyResolver propertyResolver;

    @Override
    public void setEnvironment(Environment environment) {
        this.propertyResolver=new RelaxedPropertyResolver(environment,"spring.datasource.");
    }

    @Bean(name = "masterDataSource")
    @Primary
    public DataSource masterDataSource(){
        DruidDataSource dataSource=new DruidDataSource();
        dataSource.setUrl(propertyResolver.getProperty("url"));
        dataSource.setUsername(propertyResolver.getProperty("username"));
        dataSource.setPassword(propertyResolver.getProperty("password"));
        dataSource.setDriverClassName(propertyResolver.getProperty("driver-class-name"));
        dataSource.setInitialSize(Integer.valueOf(propertyResolver.getProperty("initial-size")));
        dataSource.setMinIdle(Integer.valueOf(propertyResolver.getProperty("min-idle")));
        dataSource.setMaxWait(Long.valueOf(propertyResolver.getProperty("max-wait")));
        dataSource.setMaxActive(Integer.valueOf(propertyResolver.getProperty("max-active")));
        dataSource.setMinEvictableIdleTimeMillis(
                Long.valueOf(propertyResolver.getProperty("min-evictable-idle-time-millis")));
        return dataSource;
    }

    /**
     * mybatis-plus SQL执行效率插件【生产环境可以关闭】
     */

    @Bean
    public PerformanceInterceptor performanceInterceptor() {
        return new PerformanceInterceptor();
    }

    /**
     * mybatis-plus分页插件<br>
     * 文档：http://mp.baomidou.com<br>
     */

    @Bean
    public PaginationInterceptor paginationInterceptor() {

        PaginationInterceptor paginationInterceptor=new PaginationInterceptor();
        paginationInterceptor.setDialectType("mysql");
        return  paginationInterceptor;
    }

    @Bean(name = "masterSqlSessionFactory")
    @Primary
    public MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean(@Qualifier("masterDataSource") DataSource masterDataSource) throws Exception{
        final MybatisSqlSessionFactoryBean sqlSessionFactoryBean=new MybatisSqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(masterDataSource);
        if (!ObjectUtils.isEmpty(this.interceptors)) {
            sqlSessionFactoryBean.setPlugins(this.interceptors);
        }

        // MP 全局配置，更多内容进入类看注释
        GlobalConfiguration globalConfig = new GlobalConfiguration();
        //配置公共字段自动填写
//        globalConfig.setMetaObjectHandler(myMetaObjectHandler);
        globalConfig.setDbType(DBType.MYSQL.name());
        // ID 策略 AUTO->`0`("数据库ID自增") INPUT->`1`(用户输入ID") ID_WORKER->`2`("全局唯一ID") UUID->`3`("全局唯一ID")
        globalConfig.setIdType(3);
        sqlSessionFactoryBean.setGlobalConfig(globalConfig);
        MybatisConfiguration mc = new MybatisConfiguration();
        mc.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
        sqlSessionFactoryBean.setConfiguration(mc);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MasterDruidDataSourceConfig.MAPPERLOCATIONS));
        return  sqlSessionFactoryBean;
    }
}
